package com.yunkeji.api.common.controller;

import cn.hutool.core.util.ObjectUtil;
import com.yunkeji.api.common.bo.AliCallBackBo;
import com.yunkeji.common.core.bo.FileUpload;
import com.yunkeji.api.common.service.ISysOssService;
import com.yunkeji.api.common.vo.OssVo;
import com.yunkeji.common.core.controller.BaseController;
import com.yunkeji.common.core.domain.R;
import com.yunkeji.common.core.domain.vo.SysOssVo;
import com.yunkeji.common.enums.FileTypeEnum;
import com.yunkeji.common.helper.LoginHelper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

/**
 * 文件上传
 *
 * @author 老张
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/v1/file")
public class FileController extends BaseController {

    private final ISysOssService iSysOssService;
    /**
     * 上传文件,HTTP上传 1=语音2=相册3=视频4=头像
     *
     * @param file 文件
     */
    @PostMapping(value = "/uploadHttps/{fileType}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<OssVo> uploadHttps(
            @RequestPart("file") MultipartFile file, @PathVariable Integer fileType) {

        String path =
                FileTypeEnum.getPathByCode(fileType)
                        .replace("uid", LoginHelper.getPlatformId().toString());
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file, path);
        return R.ok(
                OssVo.builder()
                        //   .url(oss.getUrl())
                        .fileName(oss.getFileName())
                        //   .ossId(oss.getOssId())
                        .build());
    }

    /** 上传文件,前端直传 1=语音2=相册3=视频4=头像 */
    @PostMapping(value = "/uploadWeb")
    public R uploadWeb(@Valid @RequestBody FileUpload fileType) {
        return R.ok(iSysOssService.upload(fileType));
    }

    /** 上传成功的回调 */
    @PostMapping(value = "/aliCallback")
    @SneakyThrows
    public R aliCallback(@ModelAttribute AliCallBackBo aliCallBackBo) {
        iSysOssService.aliCallback(aliCallBackBo);
        return R.ok();
    }
}
